package management;

import com.toedter.calendar.JDateChooser;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

// 消费信息类，用于存储和传递消费信息相关数据
class Consumption {
        private int id;
        private String consumptionProject;
        private String dateTime;
        private double amount;
        private String category;
        private String remark;

        public Consumption(int id, String consumptionProject, String dateTime, double amount, String category) {
                this.id = id;
                this.consumptionProject = consumptionProject;
                this.dateTime = dateTime;
                this.amount = amount;
                this.category = category;
        }

        public int getId() {
                return id;
        }

        public void setId(int id) {
                this.id = id;
        }

        public String getConsumptionProject() {
                return consumptionProject;
        }

        public void setConsumptionProject(String consumptionProject) {
                this.consumptionProject = consumptionProject;
        }

        public String getDateTime() {
                return dateTime;
        }

        public void setDateTime(String dateTime) {
                this.dateTime = dateTime;
        }

        public double getAmount() {
                return amount;
        }

        public void setAmount(double amount) {
                this.amount = amount;
        }

        public String getCategory() {
                return category;
        }

        public void setCategory(String category) {
                this.category = category;
        }
}

// 根据id获取消费信息

// 更新消费信息

// 主修改窗口类，整合了所有相关功能
public class Modify extends JFrame {
        Connection connection;

        public void csql() {
                try {
                        Class.forName("com.mysql.cj.jdbc.Driver");
                } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                        System.err.println("加载错误");
                }
                String username = "root";
                String password = "root";
                String url = "jdbc:mysql://localhost:3306/project";
                try {
                        connection = DriverManager.getConnection(
                                url,
                                username,
                                password
                        );
                } catch (SQLException throwables) {
                        throwables.printStackTrace();
                        System.err.println("数据库在连接期间，出现错误！");
                }
        }

        //检查数据库中是否存在某个id值
        private boolean checkIdExists(int id) {
                String checkSql = "SELECT COUNT(*) FROM consumer WHERE consumption_id =(?)";
                try (PreparedStatement pstmt = connection.prepareStatement(checkSql)) {
                        pstmt.setInt(1, id);
                        ResultSet rs = pstmt.executeQuery();
                        if (rs.next()) {
                                int count = rs.getInt(1);
                                return count > 0;
                        }
                } catch (SQLException ex) {
                        ex.printStackTrace();
                }
                return false;
        }
        public Consumption getConsumptionById(int id) {
                String sql = "SELECT * FROM consumer WHERE consumption_id =?";
                Consumption consumption = null;
                try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
                        pstmt.setInt(1, id);
                        ResultSet rs = pstmt.executeQuery();
                        if (rs.next()) {
                                String consumptionProject = rs.getString("consumption_project");
                                String dateTime = rs.getString("date_time");
                                double amount = rs.getDouble("number");
                                String category = rs.getString("category");

                                consumption = new Consumption(id, consumptionProject, dateTime, amount, category);
                        }
                } catch (SQLException e) {
                        e.printStackTrace();
                }
                return consumption;
        }

        public void updateConsumption(Consumption updatedConsumption) {
                String sql = "UPDATE consumer SET consumer_id=?, consumption_project =?, date_time =?, number =?, category =?  WHERE consumption_id =?";
                try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
                        pstmt.setString(1, Management.getID());
                        pstmt.setString(2, updatedConsumption.getConsumptionProject());

                        pstmt.setString(3, updatedConsumption.getDateTime());
                        pstmt.setDouble(4, updatedConsumption.getAmount());
                        pstmt.setString(5, updatedConsumption.getCategory());
                        pstmt.setInt(6, updatedConsumption.getId());
                        pstmt.executeUpdate();
                } catch (SQLException e) {
                        e.printStackTrace();
                }
        }

        JButton ProjectB;
        JButton TimeB;
        JButton NumB;
        JButton CategoryB;
        JPanel ModifyPanel;

        // 构建主修改窗口界面
        public void ModifyWindow() {
                csql();
                ModifyPanel = new JPanel();
                setContentPane(ModifyPanel);
                this.setTitle("修改消费信息");
                setLayout(null);
                ModifyPanel.setBackground(Color.lightGray);

                // 添加用于提示的JLabel
                JLabel tipLabel = new JLabel("请选择您要修改的内容");
                tipLabel.setBounds(180, 10, 200, 20);  // 根据界面布局调整合适的位置
                Font font = new Font("宋体", Font.BOLD, 14);  // 设置字体及字号，可根据喜好调整
                tipLabel.setFont(font);
                ModifyPanel.add(tipLabel);

                ProjectB = new JButton("修改消费项目");
                ProjectB.setBounds(120, 40, 230, 60);
                ProjectB.setBackground(Color.orange);
                ModifyPanel.add(ProjectB);

                TimeB = new JButton("修改消费时间");
                TimeB.setBounds(120, 120, 230, 60);
                TimeB.setBackground(Color.orange);
                ModifyPanel.add(TimeB);


                NumB = new JButton("修改消费金额");
                NumB.setBounds(120, 200, 230, 60);
                NumB.setBackground(Color.orange);
                ModifyPanel.add(NumB);

                CategoryB = new JButton("修改消费类型");
                CategoryB.setBounds(120, 280, 230, 60);
                CategoryB.setBackground(Color.orange);
                ModifyPanel.add(CategoryB);

                //                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setBounds(400, 300, 530, 456);

                ProjectB.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                modifyProject();
                        }
                });

                TimeB.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                modifyTime();
                        }
                });

                NumB.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                modifyAmount();
                        }
                });

                CategoryB.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                modifyCategory();
                        }
                });

                setVisible(true);
        }

        // 修改消费项目的方法，包含弹出输入框获取id、展示修改窗口
        private void modifyProject() {
                String inputId = JOptionPane.showInputDialog("请输入要修改的消费信息的编号");

                if (inputId!= null &&!inputId.isEmpty()) {
                        try {
                                if(!checkIdExists(Integer.parseInt(inputId))){
                                        JOptionPane.showMessageDialog(null, "编号不存在");
                                        return;
                                }
                                int id = Integer.parseInt(inputId);
                                showModifyProjectWindow(id);
                        } catch (NumberFormatException ex) {
                                JOptionPane.showMessageDialog(null, "请输入有效的整数消费编号");
                        }
                } else {
                        JOptionPane.showMessageDialog(null, "请输入消费编号值");
                }

        }

        // 展示修改消费项目的窗口及处理修改逻辑
        private void showModifyProjectWindow(int targetId) {
                JFrame projectWindow = new JFrame("修改消费项目");
                projectWindow.setLayout(new BorderLayout());
                projectWindow.setBounds(550,450,300,150);
                JPanel inputPanel = new JPanel(new GridLayout(2, 1));
                JLabel projectLabel = new JLabel("新的消费项目:");
                JTextField projectField = new JTextField();
                inputPanel.add(projectLabel);
                inputPanel.add(projectField);

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确认修改");
                buttonPanel.add(confirmButton);

                projectWindow.add(inputPanel, BorderLayout.CENTER);
                projectWindow.add(buttonPanel, BorderLayout.SOUTH);

                confirmButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                String newProject = projectField.getText();
                                Consumption consumptionToUpdate = getConsumptionById(targetId);
                                if (consumptionToUpdate!= null) {
                                        consumptionToUpdate.setConsumptionProject(newProject);
                                        updateConsumption(consumptionToUpdate);
                                        JOptionPane.showMessageDialog(null, "消费项目修改成功");
                                        projectWindow.dispose();
                                } else {
                                        JOptionPane.showMessageDialog(null, "未找到对应消费编号，请检查输入的消费编号是否正确");
                                }
                        }
                });

                projectWindow.setVisible(true);
        }

        // 修改消费时间的方法，类似修改消费项目的流程
        private void modifyTime() {
                String inputId = JOptionPane.showInputDialog("请输入要修改的消费编号");
                if (inputId!= null &&!inputId.isEmpty()) {
                        if(!checkIdExists(Integer.parseInt(inputId))){
                                JOptionPane.showMessageDialog(null, "编号不存在");
                                return;
                        }

                        try {
                                int id = Integer.parseInt(inputId);
                                showModifyTimeWindow(id);
                        } catch (NumberFormatException ex) {
                                JOptionPane.showMessageDialog(null, "请输入有效的消费编号");
                        }
                } else {
                        JOptionPane.showMessageDialog(null, "请输入消费编号");
                }
        }

        // 展示修改消费时间的窗口及处理修改逻辑
        private void showModifyTimeWindow(int targetId) {
                JFrame timeWindow = new JFrame("修改消费时间");
                timeWindow.setSize(300, 150);
                timeWindow.setLayout(new BorderLayout());
                timeWindow.setBounds(550, 450, 300, 150);

                JPanel inputPanel = new JPanel(new GridLayout(2, 1));
                JLabel timeLabel = new JLabel("新的消费时间:");
                JDateChooser dateChooser = new JDateChooser();
                inputPanel.add(timeLabel);
                inputPanel.add(dateChooser);

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确认修改");
                buttonPanel.add(confirmButton);

                timeWindow.add(inputPanel, BorderLayout.CENTER);
                timeWindow.add(buttonPanel, BorderLayout.SOUTH);

                confirmButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                java.util.Date selectedDate = dateChooser.getDate();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String newTime = "";
                                if (selectedDate!= null) {
                                        newTime = sdf.format(selectedDate);
                                }
                                Consumption consumptionToUpdate = getConsumptionById(targetId);
                                if (consumptionToUpdate!= null) {
                                        consumptionToUpdate.setDateTime(newTime);
                                        updateConsumption(consumptionToUpdate);
                                        JOptionPane.showMessageDialog(null, "消费时间修改成功");
                                        timeWindow.dispose();
                                } else {
                                        JOptionPane.showMessageDialog(null, "未找到对应的消费编号，请检查输入的消费编号是否正确");
                                }
                        }
                });

                timeWindow.setVisible(true);
        }

        // 修改消费金额的方法，类似上述流程
        private void modifyAmount() {
                String inputId = JOptionPane.showInputDialog("请输入要修改的消费编号");
                if (inputId!= null &&!inputId.isEmpty()) {
                        try {
                                if(!checkIdExists(Integer.parseInt(inputId))){
                                        JOptionPane.showMessageDialog(null, "编号不存在");
                                        return;
                                }
                                int id = Integer.parseInt(inputId);
                                showModifyAmountWindow(id);
                        } catch (NumberFormatException ex) {
                                JOptionPane.showMessageDialog(null, "请输入有效的消费编号");
                        }
                } else {
                        JOptionPane.showMessageDialog(null, "请输入消费编号");
                }
        }

        // 展示修改消费金额的窗口及处理修改逻辑
        private void showModifyAmountWindow(int targetId) {
                JFrame amountWindow = new JFrame("修改消费金额");
                amountWindow.setSize(300, 150);
                amountWindow.setLayout(new BorderLayout());
                amountWindow.setBounds(550,450,300,150);
                JPanel inputPanel = new JPanel(new GridLayout(2, 1));
                JLabel amountLabel = new JLabel("新的消费金额:");
                JTextField amountField = new JTextField();
                inputPanel.add(amountLabel);
                inputPanel.add(amountField);

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确认修改");
                buttonPanel.add(confirmButton);

                amountWindow.add(inputPanel, BorderLayout.CENTER);
                amountWindow.add(buttonPanel, BorderLayout.SOUTH);

                confirmButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                try {
                                        double newAmount = Double.parseDouble(amountField.getText());
                                        Consumption consumptionToUpdate = getConsumptionById(targetId);
                                        if (consumptionToUpdate!= null) {
                                                consumptionToUpdate.setAmount(newAmount);
                                                updateConsumption(consumptionToUpdate);
                                                JOptionPane.showMessageDialog(null, "消费金额修改成功");
                                                amountWindow.dispose();
                                        } else {
                                                JOptionPane.showMessageDialog(null, "未找到对应消费编号，请检查输入的消费编号是否正确");
                                        }
                                } catch (NumberFormatException ex) {
                                        JOptionPane.showMessageDialog(null, "请输入有效的数字作为消费金额");
                                }
                        }
                });

                amountWindow.setVisible(true);
        }

        // 修改消费类型的方法，类似前面的修改操作流程
        private void modifyCategory() {
                String inputId = JOptionPane.showInputDialog("请输入要修改的消费编号");
                if (inputId!= null &&!inputId.isEmpty()) {
                        try {
                                if(!checkIdExists(Integer.parseInt(inputId))){
                                        JOptionPane.showMessageDialog(null, "编号不存在");
                                        return;
                                }
                                int id = Integer.parseInt(inputId);
                                showModifyCategoryWindow(id);
                        } catch (NumberFormatException ex) {
                                JOptionPane.showMessageDialog(null, "请输入有效的消费编号");
                        }
                } else {
                        JOptionPane.showMessageDialog(null, "请输入消费编号");
                }
        }

        // 展示修改消费类型的窗口及处理修改逻辑
        private void showModifyCategoryWindow(int targetId) {
                JFrame categoryWindow = new JFrame("修改消费类型");
                categoryWindow.setSize(300, 150);
                categoryWindow.setLayout(new BorderLayout());
                categoryWindow.setBounds(550,450,300,150);
                JPanel inputPanel = new JPanel(new GridLayout(2, 1));
                JLabel categoryLabel = new JLabel("新的消费类型:");
                JComboBox<String> comboBox = new JComboBox<>();
                Category category = new Category();
                List<String> list = new ArrayList<>();
                list = category.getCategories();
                for (int i = 0; i < list.size(); i++) {
                        comboBox.addItem(list.get(i));
                }
                inputPanel.add(categoryLabel);
                inputPanel.add(comboBox);

                JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                JButton confirmButton = new JButton("确认修改");
                buttonPanel.add(confirmButton);

                categoryWindow.add(inputPanel, BorderLayout.CENTER);
                categoryWindow.add(buttonPanel, BorderLayout.SOUTH);

                confirmButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                                String newCategory = (String) comboBox.getSelectedItem();
                                Consumption consumptionToUpdate = getConsumptionById(targetId);
                                if (consumptionToUpdate!= null) {
                                        consumptionToUpdate.setCategory(newCategory);
                                        updateConsumption(consumptionToUpdate);
                                        JOptionPane.showMessageDialog(null, "消费类型修改成功");
                                        categoryWindow.dispose();
                                } else {
                                        JOptionPane.showMessageDialog(null, "未找到对应消费编号，请检查输入的消费编号是否正确");
                                }
                        }
                });

                categoryWindow.setVisible(true);
        }

        public static void main(String[] args) {
                Modify modify = new Modify();
                modify.ModifyWindow();
        }
}